<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        div {
            width: 100px;
            height: 100px;
        }

        .box1 {
            background: red;
        }

        .box2 {
            background: blue;
        }

        .box3 {
            background: yellow;
        }
    </style>
</head>

<body>
    <button>111</button>
    <button>222</button>
    <button>333</button>
    <div class="box1"></div>
    <div class="box2"></div>
    <div class="box3"></div>
    <script>
        var btns = document.querySelectorAll("button");
        for (var i = 0; i < btns.length; i++) {
            //赋值每一项的下标
            btns[i].index = i;
            //每一项添加点击事件
            btns[i].onclick = function () {
                //点击打印保存的下标
                console.log(this.index);
            }
        }

        for (var i = 0; i < 3; i++) {
            (function (i) {
                setTimeout(() => {
                    console.log(i);
                }, 1000);
            })(i) // 0 1 2

        }

    </script>
</body>

</html>